package net.cloudcodex.client.main.presenter;

import net.cloudcodex.client.CloudCodexEventBus;
import net.cloudcodex.client.main.view.MainView;
import net.cloudcodex.client.main.view.MainView.Constant;
import net.cloudcodex.client.main.view.MainViewImpl;
import net.cloudcodex.client.util.rpc.SuccessCallback;
import net.cloudcodex.shared.Errors;
import net.cloudcodex.shared.dto.Result;
import net.cloudcodex.shared.dto.home.HomeDTO;
import net.cloudcodex.shared.rpc.HomeRPCAsync;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.inject.Inject;
import com.mvp4g.client.annotation.Presenter;
import com.mvp4g.client.presenter.BasePresenter;

/**
 * 
 * 
 * @author ADaroussin
 */
@Presenter(view = MainViewImpl.class)
public class MainPresenter extends BasePresenter<MainView, CloudCodexEventBus> {
	private final Constant constant;
	private HomeRPCAsync service;

	@Inject
	public MainPresenter(Constant constant, HomeRPCAsync homeService) {
		this.constant = constant;
		this.service = homeService;
	}

	@Override
	public void bind() {
		// Binding avec la vue
		view.getLogoutLink().addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent pEvent) {
				Window.Location.replace(constant.getLinkLogout()
						+ Window.Location.getHref());
			}
		});
	}

	public void onStart() {
		service.getHome(new SuccessCallback<Result<HomeDTO>>() {
			@Override
			public void onSuccess(Result<HomeDTO> result) {
				HomeDTO home = null;
				if (result != null) {
					home = result.getData();
					if ((result.hasError(Errors.NOT_REGISTERED))
							|| (home == null)) {
						eventBus.showRegisterPopup();
						return;
					}
					initTabs(home);
				}

			}
		});
	}

	private void initTabs(HomeDTO home) {
		eventBus.initHomeTab(home);
	
		if (home.getCharacters()!=null){
			eventBus.initCharactersTab(home.getCharacters());
		}
		
		if (home.getCampaigns()!=null){
			eventBus.initCampaignsTab(home.getCampaigns());
		}

		eventBus.setNickName(home.getNickname());
		eventBus.setUserId(home.getUserId());
	}

	public void onAddTab(IsWidget tab, String tabName) {
		view.addTab(tab, tabName);
	}

	public void onSelectTab(IsWidget tab) {
		view.selectTab(tab);
	}

	public void onDisplayErrorMessage(Throwable reason) {
		view.displayAlertMessage(reason.toString());
	}

	public void onDisplayAlertMessage(String message) {
		view.displayAlertMessage(message);
	}
}
